package com.starsky.common.easypoi;

import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.afterturn.easypoi.word.WordExportUtil;
import com.starsky.common.utils.DateUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xwpf.usermodel.XWPFDocument;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Excel工具类
 */
public class WordUtils {
    public static int USE_SXSSF_LIMIT = 100000;

    /**
     * 获取下载路径
     *
     * @param filePath 文件全路径
     */
    public static String getAbsoluteFile(String filePath, String fileName) {
        File desc = new File(filePath + File.separator + fileName);
        if (!desc.getParentFile().exists()) {
            desc.getParentFile().mkdirs();
        }
        return filePath;
    }

    /**
     * 获取下载路径
     *
     * @param filePath 文件全路径
     */
    public static String getAbsoluteFile(String filePath) {
        File desc = new File(filePath);
        if (!desc.getParentFile().exists()) {
            desc.getParentFile().mkdirs();
        }
        return filePath;
    }


    /**
     * 创建workbook
     *
     * @param path
     * @return
     */
    public static Workbook createWorkbook(String path, ExcelType type) {
        path = getAbsoluteFile(path);
        return createWorkbook(new File(path), type);
    }

    /**
     * 创建workbook
     *
     * @param file
     * @return
     */
    public static Workbook createWorkbook(File file, ExcelType type) {
        Workbook wb = null;
        try {
            wb = createWorkbook(new FileInputStream(file), type);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return wb;
    }

    /**
     * 创建workbook
     *
     * @param in
     * @return
     */
    public static Workbook createWorkbook(InputStream in, ExcelType type) {
        Workbook wb = null;
        try {
            if (ExcelType.XSSF.equals(type)) {
                return new XSSFWorkbook(in);
            } else {
                return new HSSFWorkbook(in);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return wb;
    }

    /**
     * 创建workbook
     *
     * @return
     */
    public static Workbook getWorkbook(ExcelType type, int size) {
        if (ExcelType.HSSF.equals(type)) {
            return new HSSFWorkbook();
        } else if (ExcelType.XSSF.equals(type)) {
            return new XSSFWorkbook();
        } else {
            return (Workbook) (size < USE_SXSSF_LIMIT ? new XSSFWorkbook() : new SXSSFWorkbook());
        }
    }

    /**
     * Excel导出单个sheet
     *
     * @param response response
     * @param fileName 文件名
     * @param document 创建导出word
     */
    public static void writeResponse(HttpServletResponse response, XWPFDocument document, String fileName) {

        try {
            response.setCharacterEncoding("UTF-8");
            response.setHeader("content-Type", "application/octet-stream;charset=utf-8");
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8") + ".xlsx");
            ServletOutputStream out = response.getOutputStream();
            document.write(out);
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * Excel导出单个sheet
     *
     * @param out      response
     * @param document 创建导出word
     */
    public static void writeResponse(OutputStream out, XWPFDocument document) {

        try {
            document.write(out);
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * Excel导出单个sheet
     *
     * @param response response
     * @param fileName 文件名
     * @param map      数据
     */
    public static void exportWord07(HttpServletResponse response,
                                    String templateUrl,
                                    String fileName,
                                    Map<String, Object> map) {
        try {
            if (StringUtils.isBlank(fileName)) {
                // 当前日期
                fileName = DateUtils.format(new Date(), null);
            }

            XWPFDocument doc = WordExportUtil.exportWord07(templateUrl, map);
            WordUtils.writeResponse(response, doc, fileName);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * Excel导出单个sheet
     *
     * @param response response
     * @param fileName 文件名
     * @param list     数据
     */
    public static void exportWord07(HttpServletResponse response,
                                    String templateUrl,
                                    String fileName,
                                    List<Map<String, Object>> list) {
        try {
            if (StringUtils.isBlank(fileName)) {
                // 当前日期
                fileName = DateUtils.format(new Date(), null);
            }

            XWPFDocument doc = WordExportUtil.exportWord07(templateUrl, list);
            WordUtils.writeResponse(response, doc, fileName);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Excel导出单个sheet
     *
     * @param response response
     * @param fileName 文件名
     * @param map     数据
     */
    public static void exportWord07(HttpServletResponse response,
                                    XWPFDocument document,
                                    String fileName,
                                    Map<String, Object> map) {
        try {
            if (StringUtils.isBlank(fileName)) {
                // 当前日期
                fileName = DateUtils.format(new Date(), null);
            }
            WordExportUtil.exportWord07(document, map);
            WordUtils.writeResponse(response, document, fileName);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * Excel导出单个sheet
     *
     * @param templateUrl 模板文件路径
     * @param filePath    文件全路径
     * @param map         数据
     */
    public static void exportWord07(String templateUrl,
                                    String filePath,
                                    Map<String, Object> map) {
        try {
            filePath = getAbsoluteFile(filePath);
            XWPFDocument doc = WordExportUtil.exportWord07(templateUrl, map);
            WordUtils.writeResponse(new FileOutputStream(filePath), doc);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static void main(String[] args) {

    }

    /**
     * 简单导出没有图片和Excel
     */
    public static void SimpleWordExport() {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("department", "Easypoi");
        map.put("person", "JueYue");
        map.put("time", "2022-07-10");
        map.put("me", "JueYue");
        map.put("date", "2015-01-03");
        map.put("mark", "0x0051");
        try {
            XWPFDocument doc = WordExportUtil.exportWord07("E:word/Simple.docx", map);
            FileOutputStream fos = new FileOutputStream("E:/home/excel/simple.docx");
            doc.write(fos);
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
